package ms.platform.system.controller;

import ms.platform.plan.dto.FactoryDto;
import ms.platform.plan.service.BusModelService;
import ms.platform.system.model.Admin;
import ms.platform.system.model.Role;
import ms.platform.system.service.AdminService;
import ms.platform.system.service.RoleService;
import ms.platform.util.PageUtils;
import ms.platform.util.SHAUtil;
import ms.platform.util.StringUtil;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/system/admin/")
public class AdminController extends BaseController {

	@Autowired
	private AdminService adminService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private BusModelService busModelService;
	
	/**
	 * 用户列表
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String list(@RequestParam Map<String,Object> map, HttpServletRequest request){
		try {
			if (!StringUtil.isNullOrBlock(map.get("username"))) {
				if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("username")))) {
					String fac = (String) map.get("username");
					map.put("username",new String(fac.getBytes("ISO-8859-1"), "utf-8"));
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		map.put("isDeleted", "0");//是否删除：0 未删除  1删除
		
		//总条数
		map.put("count", adminService.queryAdminCount(map));
		
		List<Admin> list = adminService.queryAdminListByCondition(PageUtils.Page(request,map));
		
		request.setAttribute("list", list);
		PageUtils.calculate(map);
		Map<String, Object> mapRole = new HashMap<String, Object>();
		mapRole.put("isUsed", "1");
		
		List<Role> roleList = roleService.queryRoleListByCondition(mapRole);
		request.setAttribute("roleList", roleList);
		request.getSession().setAttribute("adminListByCondition", map);
		return "system/admin/list";
	}
	
	/**
	 * 跳转到添加页面
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toAdd")
	public String toAdd(HttpServletRequest request){
		List<FactoryDto> factoryList = busModelService.queryAllFactory("");
		request.setAttribute("factory", factoryList);
		return "system/admin/add";
	}
	
	/**
	 * 跳转到用户编辑页面
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toEdit")
	public String toEdit(Integer id, HttpServletRequest request){
		if(id != null){
			Admin admin1 = adminService.queryAdminById(id);
			request.setAttribute("admin1", admin1);
		}
		List<FactoryDto> factoryList = busModelService.queryAllFactory("");
		request.setAttribute("factory", factoryList);
		return "system/admin/edit";
	}
	
	/**
	 * 跳转到密码修改页面
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toEditPassword")
	public String toEditPassword(Integer id, HttpServletRequest request){
		if(id != null){
			Admin admin1 = adminService.queryAdminById(id);
			request.setAttribute("admin1", admin1);
		}
		return "system/admin/editpassword";
	}
	/**
	 * 添加用户
	 * @param admin
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	public Object save(Admin admin1, HttpServletRequest request){
		
		String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		
		admin1.setCreateBy(adminId);
		admin1.setPassword(SHAUtil.SHA256(admin1.getPassword()));
		
		adminService.insert(admin1);
		return returnSuccess("操作成功", admin1);
	}
	
	/**
	 * 检查用户是否已经存在
	 * @param username
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getUserByName")
	@ResponseBody
	public String getUserByName(String username, HttpServletRequest request){
		boolean result = true;
		Admin admin = adminService.queryAdminByUsername(username.trim());
		if(admin != null){
			result = false;
		}
		Map<String, Boolean> map = new HashMap<>();
        map.put("valid", result);
		 ObjectMapper mapper = new ObjectMapper();
	        String resultString = "";
	        try {
	            resultString = mapper.writeValueAsString(map);
	        } catch (JsonProcessingException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
				e.printStackTrace();
			}
	        return resultString;
	}
	
	
	/**
	 * 检查用户录入的手机号是否在数据库中已存在
	 * @param username
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/validateByPhone")
	@ResponseBody
	public String validateByPhone(String phone, HttpServletRequest request){
		boolean result = true;
		int count = adminService.validateByPhone(phone.trim());
		if(count >= 1){
			result = false;
		}
		Map<String, Boolean> map = new HashMap<>();
        map.put("valid", result);
		 ObjectMapper mapper = new ObjectMapper();
	        String resultString = "";
	        try {
	            resultString = mapper.writeValueAsString(map);
	            System.out.println(resultString);
	        } catch (JsonProcessingException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
				e.printStackTrace();
			}
	        return resultString;
	}
	
	/**
	 * 编辑修改用户
	 * @param admin
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/editUser")
	@ResponseBody
	public Object editUser(Admin admin, HttpServletRequest request){
		if(admin.getId() != null){
			Admin adminById = adminService.queryAdminById(admin.getId());
			String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
			admin.setUpdateBy(adminId);
			admin.setPassword(SHAUtil.SHA256(admin.getPassword()));
			if (admin.getUsername().equals(adminById.getUsername())) {
				adminService.update(admin);
			}else {
				int count = adminService.queryCountByUsername(admin.getUsername());
				if (count==0) {
					adminService.update(admin);
				}else{
					return returnError(1, "用户名已存在，请重新填写", admin);
				}
			}
		}
		return returnSuccess("操作成功", admin);
	}
	/**
	 * 修改用户密码
	 * @param admin
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/editPassword")
	@ResponseBody
	public Object editPassword(Admin admin, HttpServletRequest request){
		if(admin.getId() != null){
			String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
			admin.setUpdateBy(adminId);
			admin.setPassword(SHAUtil.SHA256(admin.getPassword()));
			adminService.update(admin);
		}
		return returnSuccess("操作成功", admin);
	}
	
	/**
	 * 禁用账户
	 * @param admin
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/disabledAdmin")
	@ResponseBody
	public Object disabledAdmin(Admin admin, HttpServletRequest request){
		String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		admin.setUpdateBy(adminId);
		adminService.updateIsUsed(admin);
		return returnSuccess("操作成功",admin.getId());
	}
	
	/**
	 * 删除用户
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deleteUser")
	@ResponseBody
	public Object deleteUser(Integer id, HttpServletRequest request){
		String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		adminService.deleteUserById(id, adminId);
		return returnSuccess("操作成功",id);
	}
	
	@RequestMapping(value = "/sha")
	public String sha(HttpServletRequest request){
		List<Admin> list = adminService.getAllUaer();
		for (Admin admin : list) {
			admin.setPassword(SHAUtil.SHA256(admin.getPassword()));
			adminService.update(admin);
		}
		return "";
	}
	
}
